<template>
  <div class="container">
    <el-dialog
      title="新增标签"
      @close="handleClose"
      :visible.sync="isDialogShow"
      width="50%"
      @open="loadSubjectList"
      :before-close="closeDialog"
    >
      <el-form
        :model="addForm"
        :rules="tagNameRules"
        label-width="100px"
        ref="addFormRef"
      >
        <el-form-item v-if="!idFromSubject" label="所属学科:">
          <el-select
            v-model="addForm.subjectID"
            placeholder="请选择所属学科"
            style="width: 300px;"
          >
            <el-option
              :label="subject.subjectName"
              :value="subject.id"
              v-for="subject in subjectsList"
              :key="subject.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="目录名称:" prop="tagName" style="width: 400px;">
          <el-input v-model="addForm.tagName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onCancel">取 消</el-button>
        <el-button type="primary" @click="onAddFrom">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addTag, getSubjectList } from "@/api/hmmm/tags";
export default {
  name: "Dialog",
  props: ["showAddDialogSon", "idFromSubject", "isDialogShow"],
  data() {
    return {
      // showAddDialog: false,
      // 新增的对象参数
      addForm: {
        subjectID: this.$route.query.id || "",
        tagName: ""
      },
      // 学科列表
      subjectsList: [],
      // 格式验证
      tagNameRules: {
        tagName: [
          { required: true, message: "请输入目录名称", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    // 通知父组件关掉dialog
    onCancel() {
      this.$emit("cancelDialog", false);
    },
    async onAddFrom() {
      try {
        this.addForm.subjectID = +this.addForm.subjectID;
        await addTag({
          subjectID: this.addForm.subjectID,
          tagName: this.addForm.tagName
        });
        this.$emit("loadList");
        this.$emit("cancelDialog", false);
        this.$message.success("修改成功");
      } catch (error) {
        return this.$message.error("修改失败!");
      }
    },
    handleClose() {
      this.$refs.addFormRef.resetFields();
      this.addForm.subjectID = "";
    },
    closeDialog() {
      this.$emit("colsePageDialog");
    },
    // 学科下拉框数据回显
    async loadSubjectList(data) {
      try {
        const { data: res } = await getSubjectList(data);
        this.subjectsList = res.items;
      } catch (error) {
        this.$message.error("学科列表获取失败");
      }
    }
  }
};
</script>

<style scoped lang="less"></style>
